package com.orcamento.entity;

import javax.persistence.AttributeOverride;
import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;

import org.hibernate.annotations.Parameter;
import org.hibernate.annotations.Type;
import org.joda.time.DateTime;

import com.orcamento.util.Money;

@Entity
@Table(name="Transferencia")
public class Exchange {

	@Id
	@SequenceGenerator(name="transference_id", sequenceName="transference_id")
	@GeneratedValue(generator="transference_id", strategy=GenerationType.AUTO)
	@Column(name="IDTransferencia")
	private Long id;
	@Embedded
	@AttributeOverride(name="value", column=@Column(name="FoValor", nullable=false))
	private Money value;
	@Column(name="DtData")
	@Type(
			type="org.jadira.usertype.dateandtime.joda.PersistentDateTime", 
			parameters = { 
					@Parameter(name = "databaseZone", value = "jvm"),
					@Parameter(name = "javaZone", value = "jvm")
			}
		 )
	private DateTime date;
	
	@ManyToOne(targetEntity=Fund.class)
	@JoinColumn(name="IDFundoOrigem", referencedColumnName="IDFundo", nullable=false)
	private Fund origin;
	@ManyToOne(targetEntity=Fund.class)
	@JoinColumn(name="IDFundoDestino", referencedColumnName="IDFundo", nullable=false)
	private Fund destiny;
	@ManyToOne(targetEntity=Account.class)
	@JoinColumn(name="IDConta", referencedColumnName="IDPatrimonio", nullable=false)
	private Account account;

	public Boolean isValid() {
		if( origin == null || origin.getId() == null ) {
			return false;
		} 
		if( destiny == null || destiny.getId() == null ) {
			return false;
		}
		if( value == null || ! value.greaterThanZero() ) {
			return false;
		}
		return ! origin.getId().equals( destiny.getId() );
	}
	
	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}
	public Fund getOrigin() {
		return origin;
	}
	public void setOrigin(Fund origin) {
		this.origin = origin;
	}
	public Money getValue() {
		return value;
	}
	public void setValue(Money value) {
		this.value = value;
	}
	public DateTime getDate() {
		return date;
	}
	public void setDate(DateTime date) {
		this.date = date;
	}
	public Fund getDestiny() {
		return destiny;
	}
	public void setDestiny(Fund destiny) {
		this.destiny = destiny;
	}

	public Account getAccount() {
		return account;
	}

	public void setAccount(Account account) {
		this.account = account;
	}

}
